<template>
  <el-drawer
    v-model="visible"
    title="组织用户管理"
    direction="rtl"
    size="50%"
    @close="handleClose"
  >
    <div class="user-management-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton animated>
          <template #template>
            <el-skeleton-item variant="p" style="width: 100%; height: 400px" />
          </template>
        </el-skeleton>
      </div>
      
      <!-- 内容区域 -->
      <div v-else class="content-container">
        <!-- 添加用户表单 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>添加现有用户</span>
            </div>
          </template>
          <el-form
            ref="addUserFormRef"
            :model="addUserForm"
            :rules="addUserRules"
            label-width="80px"
            v-loading="addUserLoading"
          >
            <el-form-item label="选择用户" prop="userId">
              <el-select
                v-model="addUserForm.userId"
                placeholder="请选择用户"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="user in availableUsers"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="角色" prop="role">
              <el-input
                v-model="addUserForm.role"
                placeholder="请输入角色"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                @click="handleAddUser"
                :loading="addUserLoading"
              >
                添加用户
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 邀请用户表单 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>邀请新用户</span>
            </div>
          </template>
          <el-form
            ref="addInvitationFormRef"
            :model="addInvitationForm"
            :rules="addInvitationRules"
            label-width="80px"
            v-loading="addInvitationLoading"
          >
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="addInvitationForm.email"
                placeholder="请输入邮箱地址"
                type="email"
              />
            </el-form-item>
            
            <el-form-item label="角色" prop="role">
              <el-input
                v-model="addInvitationForm.role"
                placeholder="请输入角色"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                @click="handleCreateInvitation"
                :loading="addInvitationLoading"
              >
                生成邀请链接
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 组织成员列表 -->
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>组织成员</span>
              <el-button type="primary" link @click="loadUsers">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-table
            :data="organizationUsers"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="user.name" label="用户名" min-width="120" />
            <el-table-column prop="role" label="角色" width="120" />
            <el-table-column prop="createdAt" label="加入时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="danger"
                  @click="handleRemoveUser(row)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="organizationUsers.length === 0" class="empty-state">
            <el-empty description="暂无组织成员" />
          </div>
        </el-card>
        
        <!-- 待接受邀请列表 -->
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>待接受邀请</span>
              <el-button type="primary" link @click="loadInvitations">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-table
            :data="invitations"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="email" label="邮箱" min-width="150" />
            <el-table-column prop="role" label="角色" width="120" />
            <el-table-column prop="createdAt" label="邀请时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="warning"
                  @click="handleRevokeInvitation(row)"
                >
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="invitations.length === 0" class="empty-state">
            <el-empty description="暂无待接受邀请" />
          </div>
        </el-card>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { systemAPI } from '@/api/system'
import { organizationAPI } from '@/api/organization'
import { invitationAPI } from '@/api/invitation'

// Props定义
const props = defineProps<{
  modelValue: boolean
  organization: any
}>()

// Emit定义
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const addUserLoading = ref(false)
const addInvitationLoading = ref(false)

// 表单引用
const addUserFormRef = ref()
const addInvitationFormRef = ref()

// 用户数据
const availableUsers = ref<any[]>([])
const organizationUsers = ref<any[]>([])
const invitations = ref<any[]>([])

// 组织ID
const organizationId = ref<number | null>(null)

// 添加用户表单
const addUserForm = reactive({
  userId: undefined as number | undefined,
  role: ''
})

// 添加用户表单验证规则
const addUserRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请输入角色', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 邀请用户表单
const addInvitationForm = reactive({
  email: '',
  role: ''
})

// 邀请用户表单验证规则
const addInvitationRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请输入角色', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    // 当抽屉打开时，加载数据
    organizationId.value = props.organization?.id || null
    loadUsers()
    loadInvitations()
  }
})

// 监听visible变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
  if (!newVal) {
    // 重置表单
    addUserForm.userId = undefined
    addUserForm.role = ''
    addInvitationForm.email = ''
    addInvitationForm.role = ''
  }
})

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    // 获取所有用户
    // @ts-ignore
    const userResponse = await systemAPI.getUsers({ page: 1, limit: 1000 })
    if (userResponse.success) {
      availableUsers.value = userResponse.data.list || []
    }
    
    // 获取组织用户
    // @ts-ignore
    const orgResponse = await organizationAPI.getOrganization(props.organization.id)
    if (orgResponse.success) {
      organizationUsers.value = orgResponse.data?.users || []
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    ElMessage.error('加载用户失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const loadInvitations = async () => {
  try {
    // @ts-ignore
    const response = await invitationAPI.getOrganizationInvitations(props.organization.id)
    if (response.success) {
      invitations.value = response.data || []
    }
  } catch (error) {
    console.error('加载邀请列表失败:', error)
  }
}

const handleAddUser = async () => {
  if (!addUserFormRef.value) return
  
  await addUserFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      addUserLoading.value = true
      try {
        // @ts-ignore
        await organizationAPI.addUserToOrganization({
          userId: addUserForm.userId,
          organizationId: organizationId.value,
          role: addUserForm.role
        })
        
        ElMessage.success('用户添加成功')
        addUserForm.userId = undefined
        addUserForm.role = ''
        await loadUsers()
        emit('refresh')
      } catch (error) {
        console.error('添加用户失败:', error)
        ElMessage.error('添加用户失败: ' + (error as Error).message)
      } finally {
        addUserLoading.value = false
      }
    }
  })
}

const handleCreateInvitation = async () => {
  if (!addInvitationFormRef.value) return
  
  await addInvitationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      addInvitationLoading.value = true
      try {
        // @ts-ignore
        const response = await invitationAPI.generateInvitation({
          organizationId: organizationId.value,
          email: addInvitationForm.email,
          role: addInvitationForm.role
        })
        
        if (response.success) {
          ElMessage.success('邀请链接已生成，请将链接发送给被邀请人')
          addInvitationForm.email = ''
          addInvitationForm.role = ''
          await loadInvitations()
        } else {
          ElMessage.error(response.message || '生成邀请链接失败')
        }
      } catch (error) {
        console.error('生成邀请链接失败:', error)
        ElMessage.error('生成邀请链接失败: ' + (error as Error).message)
      } finally {
        addInvitationLoading.value = false
      }
    }
  })
}

const handleRevokeInvitation = async (invitation: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤销对 ${invitation.email} 的邀请吗？`,
      '撤销确认',
      {
        type: 'warning',
        confirmButtonText: '确定撤销',
        cancelButtonText: '取消'
      }
    )
    
    // @ts-ignore
    const response = await invitationAPI.revokeInvitation(invitation.id)
    if (response.success) {
      ElMessage.success('邀请已撤销')
      await loadInvitations()
    } else {
      ElMessage.error(response.message || '撤销邀请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤销邀请失败:', error)
      ElMessage.error('撤销邀请失败: ' + (error as Error).message)
    }
  }
}

const handleRemoveUser = async (userOrg: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要将用户 "${userOrg.user.name}" 从组织中移除吗？`,
      '移除确认',
      {
        type: 'warning',
        confirmButtonText: '确定移除',
        cancelButtonText: '取消'
      }
    )
    
    // @ts-ignore
    await organizationAPI.removeUserFromOrganization({
      userId: userOrg.userId,
      organizationId: organizationId.value
    })
    
    ElMessage.success('用户移除成功')
    await loadUsers()
    emit('refresh')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除用户失败:', error)
      ElMessage.error('移除用户失败: ' + (error as Error).message)
    }
  }
}

const handleClose = () => {
  visible.value = false
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  // 组件挂载时的初始化逻辑
})
</script>

<style scoped>
.user-management-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
  padding: 20px 0;
}

.form-card,
.table-card {
  flex-shrink: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  padding: 40px 0;
}

/* 移动端适配 */
@media (max-width: 767px) {
  .user-management-container {
    padding: 12px;
  }
  
  .content-container {
    gap: 16px;
  }
}
</style>